package com.spark.gaea.utils;

import com.spark.gaea.config.service.easyzk.ConfigNode;
import org.springframework.core.env.Environment;

import java.text.NumberFormat;
import java.util.regex.Pattern;

public final class StringUtil {
	private static final Pattern REGEX_PASSWORD_QUERYSTRING;
	private static final Pattern REGEX_PASSWORD_JSON;

	public static String cleanString(final String stringToClean) {
		String cleanResult = "";
		if (stringToClean != null) {
			cleanResult = StringUtil.REGEX_PASSWORD_QUERYSTRING.matcher(stringToClean).replaceAll("");
			cleanResult = StringUtil.REGEX_PASSWORD_JSON.matcher(cleanResult).replaceAll("");
		}
		return cleanResult;
	}

	public static String getProperty(final ConfigNode configNode, final Environment env, final String key) {
		return getProperty(configNode, env, key, null);
	}

	public static String getProperty(final ConfigNode configNode, final Environment env, final String key,
			final String defaultValue) {
		if (configNode == null) {
			return env.getProperty(key, defaultValue);
		}
		return configNode.getProperty(key, defaultValue);
	}

	public static String padLeft(final int number, final int length) {
		final NumberFormat formatter = NumberFormat.getNumberInstance();
		formatter.setMinimumIntegerDigits(length);
		formatter.setGroupingUsed(false);
		return formatter.format(number);
	}

	static {
		REGEX_PASSWORD_QUERYSTRING = Pattern.compile("&?(password|accesskey|secretkey)=.*?(?=[&'\"])");
		REGEX_PASSWORD_JSON = Pattern.compile("\"(password|accesskey|secretkey)\":\".*?\",?");
	}
}
